import React, { useReducer, useEffect } from 'react';

const initState = {
    count: 0,
    step: 1
}

const Reducer02 = ({ step }) => {
    const reducer = (state, action) => {
        const { count } = state
        if (action.type === 'tick') {
            return { count: count + step, step }
        } else if (action.type === 'step') {
            return { count, step: action.step }
        }
    }
    const [state, dispatch] = useReducer(reducer, initState)
    const { count } = state

    useEffect(() => {
        const t = setInterval(() => {
            dispatch({ type: 'tick' })
        }, 1000)
        return () => [
            clearInterval(t)
        ]
    }, [])

    return (
        <div>
            <h2>使用reducer,step来自于props</h2>
            <p>{count}</p>
            <p>可以把reducer写到组件内获取step。但这种模式会使一些优化失效，所以应该避免滥用——reducer随着每次组件渲染会生成一份新的。</p>
            <p>useReducer可以理解为是Hooks的“作弊模式”。它可以把更新逻辑和描述发生了什么分开。结果是，这可以帮助我移除不必需的依赖，避免不必要的effect调用。</p>
        </div>
    )
}

export default Reducer02;
